//
//  SASroreKit.m
//  01_kakin
//
//  Created by jon due on 12/04/12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SASroreKit.h"

@implementation SASroreKit

@synthesize delegate = _delegate;
@synthesize appDelegate = _appDelegate;
@synthesize products = _products;
@synthesize errString = _errString;


-(id)initStoreKit{
    
    self = [ super init ];
    if (self) {
        
        // オブサーバに登録
        [[SKPaymentQueue defaultQueue]addTransactionObserver:self];
        
    }
    return self;
}

-(void)dealloc{
    
    [ _appDelegate release ];
    [ _products release ];
    [ _errString release ];
    
    [ super dealloc ];
}

// 課金処理の前
-(void)startCheck{
    
    //SKPaymentQueueのオブザーバーとして登録
	[[SKPaymentQueue defaultQueue]addTransactionObserver:self];
	
	Reachability* curReach = [Reachability reachabilityForInternetConnection];
	NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
	
	//ネットワーク判定
	if ([curReach currentReachabilityStatus]==NotReachable){
        // newtworkFaildDelegate
        [ self.delegate didFaildNetwork:self.errString ];
        return;
	}
	//デバイスの機能制限
	if([SKPaymentQueue canMakePayments]==NO){
		// deviceFaildDelegate
        
        return;
	}
	
	//requestCountを初期化
	UnfinishedCount = 0;
	
    // 課金処理
	[self productRequest];    
}

//プロダクトIDの集合を生成
-(void)productRequest{
    
    SKProductsRequest *request= [[SKProductsRequest alloc]
                                 initWithProductIdentifiers: [NSSet setWithObject: App_productName]];
    request.delegate = self;
    
    // リクエストカウントをインクリメント
	UnfinishedCount++;
	NSLog(@"%d",UnfinishedCount);
    
    [request start];

}


/* ============================================================================== */
#pragma mark - SKProductsRequest Delegate
/* ============================================================================== */

// 
- (void)requestDidFinish:(SKRequest *)request{
    
	[request release];
	NSLog(@"Request finished.");
    
}

// 
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    
    // リクエストが複数ないかチェック
	if(UnfinishedCount > 2){
        
		//[indicator removeIndicator];
		self.errString = [NSMutableString stringWithFormat:@"Error: Could not contact App Store properly, %@", [error localizedDescription]];
        
        // Delegate
        
        
    }else {
        
        // リクエストが1件の場合start
		[self productRequest];
        
	}
}

// レスポンスを受け取った時点で呼び出される。データ受信よりも前なので注意
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    if (response == nil) {
        NSLog(@"Product Response is nil");
        return;
    }
    
    // 確認できなかったidentifierをログに記録
    for (NSString *identifier in response.invalidProductIdentifiers) {
        NSLog(@"invalid product identifier: %@", identifier);
    }
    
    for (SKProduct *product in response.products ) {
        NSLog(@"valid product identifier: %@", product.productIdentifier);
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    
    return;
	
	self.products = [[[response products] lastObject]retain];
    
	if (!self.products){
        
		if(UnfinishedCount > 2){
			
            //[indicator removeIndicator];
			self.errString = [NSMutableString stringWithFormat:@"no product ids:%@",[[response invalidProductIdentifiers] description]];
            
            // Delegateへ
			
            
			return;
		}else {
            
            // 課金処理start
			[self productRequest];
			return;
		}
    }
    
    //[indicator removeIndicator];
    
	[self purchase];
}


/* ============================================================================== */
#pragma mark - SKPaymentQueue observerMethod
/* ============================================================================== */

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray*)transactions{
	
	//購入処理を取得
	for(SKPaymentTransaction* transaction in transactions){
		
		//購入処理の状態を調べる
		const char *sql = "Update UserInfo Set isPurchase =1 Where id = 1";
		switch (transaction.transactionState) {
            
			case SKPaymentTransactionStatePurchasing:
                //購入中の場合	
				[self repurchase ];
				
				break;
                
			case SKPaymentTransactionStatePurchased:
                //購入処理が成功した場合
				
                //TODO 購入処理
				self.appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
				self.appDelegate.isPurchase = YES;
				
                // データベース
//				[Coffee Update_stmt:[appDelegate getDBPath] SQL:(char *)sql];
//				bt1.hidden = YES;
				
				[self completedPurchaseTransaction:transaction];
				//購入処理完了
				[queue finishTransaction:transaction];
				//[indicator removeIndicator];
				
				break;
                
			case SKPaymentTransactionStateFailed:
                //購入処理失敗
				if(UnfinishedCount > 2){
                    
					[self handleFailedTransaction:transaction]; 
					//[indicator removeIndicator];
                    
				}else {
                    
					UnfinishedCount++;
					[self purchase];
                    
				}
                
				break;
                
			case SKPaymentTransactionStateRestored:
                //購入処理復元
				
                //ロック解除処理
				self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
				self.appDelegate.isPurchase = YES;
				const char *sql = "Update UserInfo Set isPurchase =1 Where id = 1";

				// データベース
//				[Coffee Update_stmt:[appDelegate getDBPath] SQL:(char *)sql];	
//				bt1.hidden = YES;
                //購入処理を終了
				[queue finishTransaction:transaction];
				//[indicator removeIndicator];
				break;
                
			default:
				NSLog(@"Other transaction");
				
				break;
		}
	}
}


/* ============================================================================== */
#pragma mark - payment
/* ============================================================================== */

- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions{
    
}

- (void) handleFailedTransaction: (SKPaymentTransaction *) transaction{
    
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

- (void) completedPurchaseTransaction: (SKPaymentTransaction *) transaction{
	
	// PERFORM THE SUCCESS ACTION THAT UNLOCKS THE FEATURE HERE
	
	// Check the receipt
//	NSString *json = [NSString stringWithFormat:@"{\"receipt-data\":\"%@\"}", [transaction.transactionReceipt base64Encoding]];
//	NSString *urlsting = SANDBOX ? @"https://sandbox.itunes.apple.com/verifyReceipt" : @"https://buy.itunes.apple.com/verifyReceipt";
//	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlsting]];
//	if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");
//	
//	[urlRequest setHTTPMethod: @"POST"];
//	[urlRequest setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]];
//	
//	NSError *error;
//	NSURLResponse *response;
//	NSData *result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
//	
//	NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
//	CFShow(resultString);
//	[resultString release];
	
	// 終了したら完了処理
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction]; // do not call until you are actually finished
	
}


/* ============================================================================== */
#pragma mark - Others
/* ============================================================================== */

-(void)purchase{
    
    //[indicator showIndicator:self.view];
    SKPayment *payment = [SKPayment  paymentWithProductIdentifier:self.products.productIdentifier];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    
}

- (void)repurchase{
    
	[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}



@end
